package gov.pbc.nn.kjgl.maintenance.handler;

import gov.pbc.nn.kjgl.maintenance.entity.SysProblem;

import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.HistoryProcessInstance;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.ProcessEventHandler;

@Component(SysProblemProcessEventHandler.BEAN_ID)
public class SysProblemProcessEventHandler implements ProcessEventHandler {

	public static final String BEAN_ID = "gov.pbc.nn.kjgl.maintenance.handler.SysProblemProcessEventHandler";

	@Override
	public void end(ProcessInstance arg0, Context arg1) {

	}

	@Override
	public void start(ProcessInstance pi, Context context) {
		long pId = pi.getParentId();
		if (pId == 0)
			return;
		SysProblem problem = (SysProblem) context.getProcessService().getProcessVariable("sysProblem", pId);
		if (problem != null) {
			pi.setBusinessId(problem.getId());
			pi.setPromoter(ContextHolder.getLoginUserName());
			context.getProcessService().saveProcessVariable(pi.getId(), "sysId", problem.getSysId());
			context.getProcessService().saveProcessVariable(pi.getId(), "agree", -1);
			context.getSession().saveOrUpdate(pi);

			HistoryProcessInstance hpi = (HistoryProcessInstance) context.getSession()
					.createCriteria(HistoryProcessInstance.class).add(Restrictions.eq("processInstanceId", pi.getId()))
					.uniqueResult();
			hpi.setBusinessId(pi.getBusinessId());
			hpi.setPromoter(pi.getPromoter());
			context.getSession().update(hpi);
		}
	}

}
